C# 5 - asynch method callback with Task.ContinueWIth? [migrated]

Posted by user1142433 on Programmers See other posts from Programmers or by user1142433
Published on 2012-10-25T07:07:17Z Indexed on 2012/10/25 11:15 UTC
Read the original article Hit count: 161

Filed under:
|

I have a method that pulls some HTML via the HttpClient like so:

public static HttpClient web = new HttpClient();
public static async Task<string> GetHTMLDataAsync(string url)
{                    
    string responseBodyAsText = "";
    try
    {
       HttpResponseMessage response = await web.GetAsync(url);
       response.EnsureSuccessStatusCode();
       responseBodyAsText = await response.Content.ReadAsStringAsync();
    }
    catch (Exception e)
    {
       // Error handling
    }

    return responseBodyAsText;
}

I have another method that looks like so:

private void HtmlReadComplete(string data)
{
    // do something with the data
}

I would like to be able to call GetHTMLDataAsync and then have it call HtmlReadComplete on the UI thread when the html has been read. I naively thought this could somehow be done with something that looks like

GetHTMLDataAsync(url).ContinueWith(HtmlReadComplete);

But, I can't get the syntax correct, nor am I even sure that's the appropriate way to handle it.

Thanks in advance!

© Programmers or respective owner

Related posts about c#

Related posts about async